<template>
    <view class="login-container">
      <view class="card-container">
        <!-- 顶部登录标题区 -->
        <view class="title-area" v-if="isLoginMode">
          <!-- <image class="logo-image" src="/static/modio平台.png" mode="aspectFit"></image> -->
          <view class="title-line"></view>
        </view>
  
          <!-- 顶部注册标题区 -->
        <view class="title-area" v-else>
          <text class="brand-text">
            <text class="brand-text-normal">创建新账户</text>
          </text>
          <view class="title-line"></view>
        </view>
  
        <!-- <view v-if="platform === 'app'"> -->
        <view >
              <!-- 登录表单 -->
        <view class="form-container" v-if="isLoginMode">
          <view class="input-item" :class="{'error': errors.username}">
            <text class="icon">👤</text>
            <input 
              type="text" 
              placeholder="用户名 / 邮箱" 
              placeholder-style="color: #999; font-size: 28rpx;"
              v-model="form.username"
              @blur="validateUsername"
            />
          </view>
          <text v-if="errors.username" class="error-text">{{ errors.username }}</text>
  
          <view class="input-item" :class="{'error': errors.password}">
            <text class="icon">🔒</text>
            <input 
              type="password" 
              placeholder="密码" 
              placeholder-style="color: #999; font-size: 28rpx;"
              v-model="form.password"
              @blur="validatePassword"
            />
          </view>
          <text v-if="errors.password" class="error-text">{{ errors.password }}</text>
  
          <view class="options-row">
            <view class="checkbox-item">
              <checkbox 
                :checked="rememberMe" 
                @change="handleRememberMeChange"
                color="#FF6B9B" 
              />
              <text class="checkbox-text">下次自动登录</text>
            </view>
            <text class="forget-password" @tap="handleForgetPassword">忘记密码</text>
          </view>
  
          <button class="action-button" @tap="handleLogin">登录</button>
  
          <view class="switch-link">
            <text class="switch-text">您还没有账户？</text>
            <text class="switch-action" @tap="toggleMode">去注册</text>
          </view>
        </view>
  
        <!-- 注册表单 -->
        <view class="form-container" v-else>
  
          <view class="input-item" :class="{'error': errors.username}">
            <text class="icon">👤</text>
            <input 
              type="text" 
              placeholder="用户名 / 邮箱" 
              placeholder-style="color: #999; font-size: 28rpx;"
              v-model="form.username"
              @blur="validateUsername"
            />
          </view>
          <text v-if="errors.username" class="error-text">{{ errors.username }}</text>
  
          <!-- <view class="input-item" :class="{'error': errors.phone}">
            <text class="icon">📱</text>
            <input 
              type="text" 
              placeholder="手机号" 
              placeholder-style="color: #999; font-size: 28rpx;"
              v-model="form.phone"
              @blur="validatePhone"
            />
          </view> -->
          <text v-if="errors.phone" class="error-text">{{ errors.phone }}</text>
  
          <view class="input-item" :class="{'error': errors.password}">
            <text class="icon">🔒</text>
            <input 
              type="password" 
              placeholder="密码（至少6位，包含字母和数字）" 
              placeholder-style="color: #999; font-size: 28rpx;"
              v-model="form.password"
              @blur="validatePassword"
            />
          </view>
          <text v-if="errors.password" class="error-text">{{ errors.password }}</text>
  
          <!-- <view class="input-item" :class="{'error': errors.confirmPassword}">
            <text class="icon">🔑</text>
            <input 
              type="password" 
              placeholder="确认密码" 
              placeholder-style="color: #999; font-size: 28rpx;"
              v-model="form.confirmPassword"
              @blur="validateConfirmPassword"
            />
          </view> -->
          <text v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</text>
  
          <view class="agreement-row">
            <checkbox 
              :checked="agreed" 
              @tap="handleAgreementChange"
              color="#FF6B9B" 
            />
            <text class="agreement-text">
              我已阅读并接受
              <text class="agreement-link" @tap="openUserAgreement">用户协议</text>
              和
              <text class="agreement-link" @tap="openPrivacyPolicy">隐私政策</text>
            </text>
          </view>
  
          <button class="action-button" @tap="handleRegister">注册</button>
  
          <view class="switch-link">
            <text class="switch-text">已经有账号？</text>
            <text class="switch-action" @tap="toggleMode">去登陆</text>
          </view>
        </view>
  
        </view>
  
        <!-- 微信登录 -->
        <!-- <view v-if="platform === 'mp-weixin'">
        
          <button class="action-button" @tap="wxlogin">微信授权登录</button>
  
        </view> -->
  
    
  
      </view>
    </view>
    
    <!-- 登录/注册加载弹窗 -->
    <view class="loading-mask" v-if="isLoading">
      <view class="loading-container">
        <view class="loading-spinner"></view>
        <text class="loading-text">{{loadingText}}</text>
      </view>
    </view>
  </template>
  
  <script setup>
  import { ref, reactive } from 'vue'
  import http from '../../utils/request'
  import { useUserStore } from '../../store/user'
  import { onLoad } from '@dcloudio/uni-app'
  import { getDeviceId } from '../../utils/device'
  
  // 初始化用户store
  const userStore = useUserStore()
  
  // 响应式数据
  const isLoginMode = ref(true)
  const form = reactive({
    username: '',
    password: '',
    phone: '',
    confirmPassword: ''
  })
  const errors = reactive({
    username: '',
    password: '',
    phone: '',
    confirmPassword: ''
  })
  
  // 平台
  const platform = ref('')
  
  // 记住我
  const rememberMe = ref(false)
  
  // 同意应用协议
  const agreed = ref(false)
  
  // 加载状态
  const isLoading = ref(false)
  const loadingText = ref('登录中...')

  
  const onChooseAvatar = (e) => {
    const { avatarUrl } = e.detail 
    console.log('头像选择成功:', avatarUrl)
    avatarUrl.value = avatarUrl
  }


  
  // 页面加载时检查自动登录
  onLoad(() => {
    console.log('登录页面加载')
  })
  
  
  // 方法定义
  const toggleMode = () => {
    isLoginMode.value = !isLoginMode.value
    clearForm()
  }
  
  const clearForm = () => {
    form.username = ''
    form.password = ''
    form.phone = ''
    form.confirmPassword = ''
    errors.username = ''
    errors.password = ''
    errors.phone = ''
    errors.confirmPassword = ''
  }
  
  const validateUsername = () => {
    if (!form.username.trim()) {
      errors.username = '请输入用户名'
      return false
    }
    errors.username = ''
    return true
  }
  
  const validatePassword = () => {
    if (!form.password.trim()) {
      errors.password = '请输入密码'
      return false
    }
    
    // 注册模式下需要验证密码强度
    if (!isLoginMode.value) {
      const password = form.password.trim()
      
      // 检查密码长度
      if (password.length < 6) {
        errors.password = '密码不能少于6位'
        return false
      }
      
      // 检查是否包含字母
      const hasLetter = /[a-zA-Z]/.test(password)
      // 检查是否包含数字
      const hasNumber = /\d/.test(password)
      
      if (!hasLetter || !hasNumber) {
        errors.password = '密码必须包含字母和数字'
        return false
      }
    }
    
    errors.password = ''
    return true
  }
  
  const validatePhone = () => {
    if (!form.phone.trim()) {
      errors.phone = '请输入手机号'
      return false
    }
    
    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(form.phone.trim())) {
      errors.phone = '请输入正确的手机号格式'
      return false
    }
    
    errors.phone = ''
    return true
  }
  
  const validateConfirmPassword = () => {
    if (!form.confirmPassword.trim()) {
      errors.confirmPassword = '请输入确认密码'
      return false
    }
    if (form.confirmPassword !== form.password) {
      errors.confirmPassword = '两次密码不一致'
      return false
    }
    errors.confirmPassword = ''
    return true
  }
  
  const handleLogin = async () => {
    if (!validateUsername() || !validatePassword()) {
      return
    }
  // 设置加载状态
    isLoading.value = true
    loadingText.value = '登录中...'
    
    // 获取设备ID
    const deviceId = await getDeviceId()
    
    const loginData = {
      ...form,
      deviceId: deviceId
    }
  
     const res = await http.post('https://www.dachen.vip/api/workflow/hooks/NjhjM2FiYWVlN2Q5ZjkwYmMwZWE2ZGU1', loginData)
  
      console.log('登录响应:', res)
   
      if (!res) {
        isLoading.value = false
        console.log('您输入的账号或密码异常！')
        uni.showToast({
          title: '您输入的账号或密码异常！',
          icon: 'none'
        })

        return
        
      } else {
        console.log('登录成功');
     // 关闭加载状态
     isLoading.value = false
        uni.setStorageSync('userInfo', res.data)
        userStore.setUserInfo(JSON.parse(res.data))

        console.log('userStore', userStore.getUserInfo());
     
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/tabs/index'
          })
        }, 1500)
        return

      }
    
  }
  // 注册
  const handleRegister = async () => {
    
    if (!validateUsername() || !validatePassword() ) {
      return
    }
    
    // 确保agreed是布尔值，处理可能的字符串值
    const isAgreed = Boolean(agreed.value) && agreed.value !== 'false'
    
    if (!isAgreed) {
      uni.showToast({
        title: '请同意用户协议和隐私政策',
        icon: 'none'
      })
      return
    }
    
    // 设置加载状态
    isLoading.value = true
    loadingText.value = '注册中...'
    
    // 获取设备ID
    const deviceId = await getDeviceId()
    
    const registerData = {
      ...form,
      deviceId: deviceId
    }
  
     const res = await http.post('https://www.dachen.vip/api/workflow/hooks/NjhjMzg4YWFlN2Q5ZjkwYmMwZWEyNzYw', registerData)
  
      console.log('注册响应:', res)
   
      if (!res) {
        isLoading.value = false
        console.log('该用户名已被注册，请重新输入用户名')
        uni.showToast({
          title: '该用户名已被注册，请重新输入用户名',
          icon: 'none'
        })
        
      } else {
        console.log('该用户名未被注册，可以注册');
     // 关闭加载状态
     isLoading.value = false
        uni.setStorageSync('userInfo', res.data)
        userStore.setUserInfo(JSON.parse(res.data))

        console.log('userStore', userStore.getUserInfo());
      
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/tabs/index'
          })
        }, 1500)
        return
  
      }
  }
  
  const handleForgetPassword = () => {
    uni.showToast({
      title: '忘记密码功能开发中',
      icon: 'none'
    })
  }
  
  const openUserAgreement = () => {
    uni.showToast({
      title: '用户协议功能开发中',
      icon: 'none'
    })
  }
  
  const openPrivacyPolicy = () => {
    uni.showToast({
      title: '隐私政策功能开发中',
      icon: 'none'
    })
  }
  
  const handleAgreementChange = () => {
    console.log('agreed:', agreed.value);
    agreed.value = !agreed.value
    console.log('Updated agreed value:', agreed.value)
  }
  
  const handleRememberMeChange = () => {
    rememberMe.value = !rememberMe.value
    console.log('记住我状态:', rememberMe.value)
  }
  </script>
  
  <style scoped>
    .login-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      min-height: 100vh;
      background: linear-gradient(135deg, #E8D5FF 0%, #FFB6C1 100%);
      padding: 0 32rpx;
    }
  
    .card-container {
      width: 85%;
      max-width: 600rpx;
      background: #FFFFFF;
      border-radius: 24rpx;
      box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
      padding: 48rpx 32rpx;
      margin: 48rpx 0;
    }
  
    .title-area {
      text-align: center;
      margin-bottom: 48rpx;
    }
  
    .logo-image {
      width: 300rpx;
      height: 120rpx;
      margin: 0 auto 16rpx;
      display: block;
    }
  
    .welcome-text {
      font-size: 32rpx;
      color: #666666;
      display: block;
      margin-bottom: 16rpx;
    }
  
    .brand-text {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 48rpx;
      font-weight: bold;
      margin-bottom: 16rpx;
    }
  
    .brand-name {
      color: #000000;
    }
  
    .brand-o {
      color: #FF6B9B;
      position: relative;
      display: inline-block;
      width: 48rpx;
      height: 48rpx;
      background: #FF6B9B;
      border-radius: 50%;
      color: #FFFFFF;
      text-align: center;
      line-height: 48rpx;
      margin: 0 4rpx;
    }
  
    .brand-o::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 8rpx;
      height: 8rpx;
      background: #FFFFFF;
      border-radius: 50%;
    }
  
    .brand-text-normal {
      color: #666666;
      font-size: 32rpx;
      margin-left: 8rpx;
    }
  
    .title-line {
      width: 64rpx;
      height: 4rpx;
      background: #FF6B9B;
      margin: 8rpx auto 0;
      border-radius: 2rpx;
    }
  
    .register-title {
      font-size: 36rpx;
      color: #333333;
      font-weight: 500;
      margin-bottom: 32rpx;
    }
  
    .form-container {
      width: 100%;
    }
  
    .input-item {
      display: flex;
      align-items: center;
      background: #FFFFFF;
      border: 2rpx solid #E0E0E0;
      border-radius: 16rpx;
      padding: 0 24rpx;
      height: 104rpx;
      margin-bottom: 8rpx;
      transition: all 0.3s ease;
    }
  
    .input-item.error {
      border-color: #FF4D4F;
      border-width: 3rpx;
    }
  
    .icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 20rpx;
      opacity: 0.6;
    }
  
    input {
      flex: 1;
      font-size: 28rpx;
      color: #333333;
      height: 100%;
      border: none;
      outline: none;
    }
  
    .error-text {
      color: #FF4D4F;
      font-size: 24rpx;
      margin: 8rpx 0 16rpx 24rpx;
      display: block;
    }
  
    .options-row, .agreement-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 32rpx 0;
      font-size: 24rpx;
    }
  
    .checkbox-item {
      display: flex;
      align-items: center;
    }
  
    .checkbox-text {
      color: #666666;
      margin-left: 8rpx;
    }
  
    .forget-password {
      color: #1890FF;
      font-size: 24rpx;
    }
  
    .agreement-row {
      justify-content: flex-start;
      flex-wrap: wrap;
    }
  
    .agreement-text {
      color: #666666;
      font-size: 24rpx;
      margin-left: 8rpx;
      flex: 1;
    }
  
    .agreement-link {
      color: #1890FF;
      text-decoration: none;
    }
  
    .action-button {
      width: 100%;
      height: 96rpx;
      background: #FF6B9B;
      border: none;
      border-radius: 24rpx;
      color: #FFFFFF;
      font-size: 32rpx;
      font-weight: bold;
      margin: 32rpx 0;
      box-shadow: 0 4rpx 8rpx rgba(255, 107, 155, 0.3);
      transition: all 0.3s ease;
    }
  
    .action-button:active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 4rpx rgba(255, 107, 155, 0.3);
    }
  
    .switch-link {
      text-align: center;
      margin-top: 32rpx;
    }
  
    .switch-text {
      color: #666666;
      font-size: 28rpx;
    }
  
    .switch-action {
      color: #FF6B9B;
      font-size: 28rpx;
      margin-left: 8rpx;
      font-weight: bold;
    }
  
    /* 加载弹窗样式 */
    .loading-mask {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 9999;
    }
  
    .loading-container {
      background: #FFFFFF;
      border-radius: 24rpx;
      padding: 48rpx 64rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
    }
  
    .loading-spinner {
      width: 64rpx;
      height: 64rpx;
      border: 6rpx solid #F0F0F0;
      border-top: 6rpx solid #FF6B9B;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 24rpx;
    }
  
    .loading-text {
      font-size: 28rpx;
      color: #333333;
      font-weight: 500;
    }
  
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  
  
    .user-details {
      display: flex;
      flex-direction: column;
    }
  
    .user-nickname {
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
      margin-bottom: 4rpx;
    }
  
    .user-desc {
      font-size: 24rpx;
      color: #999999;
    }
  </style>